package cn.kgc.boot.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     *  设置 指定键值
     * @param key 键
     * @param value 值
     * @return 成功
     */
    public boolean setValue(String key, Object value){
        log.info("redis赋值字符串key：{}， val：{}", key, value);
        ValueOperations<String, Object> r = redisTemplate.opsForValue();
        r.set(key, value);
        return true;
    }

    /**
     *  获取指定键的值
     * @param key 键
     * @return 值
     */
    public Object getValue(String key){
        log.info("redis获取key：{}", key);
        ValueOperations<String, Object> r = redisTemplate.opsForValue();
        return r.get(key);
    }

    /**
     *  设置可过期的key
     * @param key 键
     * @param val 值
     * @param length 时间长度
     * @param unit 单位
     * @return 成功
     */
    public boolean setTimeValue(String key, Object val, Long length, TimeUnit unit){
        log.info("redis赋值字符串设置超时key：{}， val：{}，时间长度：{}，单位：{}", key, val, length, unit);
        ValueOperations<String, Object> r = redisTemplate.opsForValue();
        r.set(key, val, length, unit);
//        redisTemplate.expire(key, length, unit);
        return true;
    }

    /**
     *  查询key失效时间
     * @param key 键
     * @return 秒
     */
    public Long getTime(String key){
        Long expire = redisTemplate.getExpire(key);
        log.info("redis获取{}剩余超时时间{}", key, expire);
        return expire;
    }




}
